// 假数据
var datalist = [
    {
        id: 123123,
        time: "08:00",
        start: "珠海北站",
        pass: "珠海口岸",
        end: "香港机场",
        totalTime: "2",
        cars:[
            {
                carid:111,
                name: "别克商务座",
                num: "粤ABC111",
                seat:[
                    {
                        id: 0,
                        type: 0,
                        price: 188,
                        state: 0
                    },{
                        id: 1,
                        type: 1,
                        price: 178,
                        state: 0
                    },{
                        id: 2,
                        type: 1,
                        price: 178,
                        state: 1
                    },{
                        id: 3,
                        type: 2,
                        price: 168,
                        state: 0
                    },{
                        id: 4,
                        type: 2,
                        price: 168,
                        state: 0
                    },{
                        id: 5,
                        type: 2,
                        price: 168,
                        state: 0
                    }
                ]
            },
            {
                carid:222,
                name: "奔驰商务座",
                num: "粤ABC222",
                seat:[
                    {
                        id: 0,
                        type: 0,
                        price: 188,
                        state: 1
                    },{
                        id: 1,
                        type: 1,
                        price: 178,
                        state: 1
                    },{
                        id: 2,
                        type: 1,
                        price: 178,
                        state: 0
                    },{
                        id: 3,
                        type: 2,
                        price: 168,
                        state: 0
                    },{
                        id: 4,
                        type: 2,
                        price: 168,
                        state: 0
                    },{
                        id: 5,
                        type: 2,
                        price: 168,
                        state: 0
                    }
                ]
            }
        ]
    },
    {
        id: 123123,
        time: "08:20",
        start: "珠海北站",
        end: "香港机场",
        totalTime: "2",
        cars:[
            {
                carid:111,
                name: "别克商务座",
                num: "粤ABC111",
                seat:[
                    {
                        id: 0,
                        type: 0,
                        price: 188,
                        state: 0
                    },{
                        id: 1,
                        type: 1,
                        price: 178,
                        state: 0
                    },{
                        id: 2,
                        type: 1,
                        price: 178,
                        state: 1
                    },{
                        id: 3,
                        type: 2,
                        price: 168,
                        state: 0
                    },{
                        id: 4,
                        type: 2,
                        price: 168,
                        state: 0
                    },{
                        id: 5,
                        type: 2,
                        price: 168,
                        state: 0
                    }
                ]
            }
        ]
    }
];


// 查询结果
var result = {
    dateSelect: "#result_date",
    peopleSelect: "#result_people",
    schedule: "#uppage_schedule",
    list: ".result-list ul",
    datalist: [],
    submit: "#nextBtn",

    // 加载列表数据
    loadList: function(){
        var _this = this;
        var date = $(this.dateSelect).attr("date");
        var people = $(this.peopleSelect).val();

        // todo 根据date、people 以及 上一页的其他参数，查询匹配的线路班次，加载列表
        this.datalist = datalist;

        $(this.list).empty();
        $.each(this.datalist, function(index, object){
            var cars = object.cars,
                passHtml = '',
                minPrice = 0,
                carHtml = '';
            if(object.pass !="" && object.pass != undefined && object.pass != null){
                passHtml = '<span>'+ object.pass +'</span>';
            }
            $.each(cars,function(a,b){
                if(a == 0) carHtml = b.name;
                else carHtml += " 转 "+b.name;
                $.each(b.seat,function(c,d){
                    if(minPrice == 0) minPrice = d.price;
                    else if( minPrice > d.price ) minPrice = d.price
                })
            })
            $(_this.list).append(
                '<li id="'+ object.id +'">'+
                    '<div class="main-info">'+
                        '<div class="head">'+
                            '<span>'+ object.time +' 发车</span>'+
                            '<em>余 5 座</em>'+
                        '</div>'+
                        '<div class="body">'+
                            '<div class="left">'+ object.start +'</div>'+
                            '<div class="middle">'+
                                passHtml +
                            '</div>'+
                            '<div class="right">'+ object.end +'</div>'+
                            '<em class="car">'+ carHtml +'</em>'+
                        '</div>'+
                    '</div>'+
                    '<div class="sub-info">'+
                        '<span class="left">全程预计 <em>'+ object.totalTime +'小时</em></span>'+
                        '<span class="right"><em>¥'+ minPrice +'</em> 起/座</span>'+
                    '</div>'+
                '</li>'
            );
        })
        
        // 线路点击弹窗座位选择
        $(_this.list).find("li").bind("click",function(){
            seatChoose.seatShow($(this).index());
        })
    },

    // 打开日历
    scheduleShow: function(){
        $(this.schedule).show();
    },

    // 关闭日历
    scheduleHide: function(){
        var _this = this;
        $(this.schedule).addClass("hide");
        setTimeout(function(){
            $(_this.schedule).removeClass("hide").hide();
        },500);
    },

    // 初始化
    init: function() {
        var _this = this;

        // todo 日期赋值及绑定点击事件
        $(this.dateSelect)
        .attr("date","2019-03-15")
        .val("3月15日")
        .bind("click",function(){
            _this.scheduleShow();
        });

        // 关闭日期窗口
        $(this.schedule).find(".close").bind("click",function(){
            _this.scheduleHide();
        });

        // 人数变动时加载列表
        $(this.peopleSelect).change(function(){
            // 人数改变时重新加载数据
            _this.loadList();
        });

        // 关闭选座窗口
        $(seatChoose.seatBox).find(".close").bind("click",function(){
            seatChoose.seatHide();
        });

        // 绑定提交按钮
        $(this.submit).bind("click",function(){
            var cars = seatChoose.selectedInfo.cars;
            if(cars[0].seats.length == 0){
                tip.show("请选择第1程的座位");
                return
            }
            if(cars[1] != undefined && cars[1].seats.length == 0){
                tip.show("请选择第2程的座位");
                return
            }
            if(cars[1] != undefined && cars[0].seats.length != cars[1].seats.length){
                tip.show("第1程与第2程的座位数需一致");
                return
            }
            console.log(_this.selectedInfo);
            //提交参数，产生订单，跳转至确认页

            $(location).attr('href', "confirm.html");
        });

        // 加载数据
        this.loadList();
    }
};


// 座位选择弹窗
var seatChoose = {
    seatBox: "#uppage_seat",
    totalPrice: "#totalPrice",
    selectedInfo: {
        lineId: "",
        cars: [],
        price: 0
    },

    // 打开座位选择
    seatShow: function(index){
        this.init(index);
        $(this.seatBox).show();
    },

    // 关闭座位选择
    seatHide: function(){
        var _this = this;
        $(this.seatBox).addClass("hide");
        setTimeout(function(){
            $(_this.seatBox).removeClass("hide").hide();
        },500);
    },


    // 初始化弹窗内容
    init: function(index){

        var _this = this;
        var data = result.datalist[index];
        var tripBox = $(this.seatBox).find(".trip-info");

        // 初始化各项数值
        this.selectedInfo.lineId = data.id;
        this.selectedInfo.cars = [];
        this.selectedInfo.price = 0;
        $(tripBox).empty();
        $(totalPrice).text("¥ 0");


        // 创建html
        var tripHtml = [];
        if(data.pass !="" && data.pass != undefined && data.pass != null){
            tripHtml[0] = data.start + "-" + data.pass;
            tripHtml[1] = data.pass + "-" + data.end;
        }
        else{
            tripHtml[0] = data.start + "-" + data.end;
        }
        $.each(data.cars,function(index,object){
            _this.selectedInfo.cars[index] = {
                id:object.carid,
                seats:[]
            };
            var newHtml = '<li carid="'+ object.carid +'" index="'+ index +'">'+
                    '<p>第 '+ (index+1) +' 程 '+ tripHtml[index] +'</p>'+
                    '<div class="car-info">'+
                        '<h4>'+ object.name +'</h4>'+
                        '<span>已选<em>0</em>座</span>'+
                    '</div>'+
                    '<ul class="seat-list">';
            $.each(object.seat,function(a,b){
                var seatName,seatPrice,seatClass="";
                if(b.type == 0) seatName="前排";
                if(b.type == 1) seatName="中排";
                if(b.type == 2) seatName="后排";
                if(b.state == 0) {
                    seatPrice = "¥"+b.price;
                }
                else {
                    seatClass = "over";
                    seatPrice = "已占座";
                }
                newHtml += '<li class="animate '+ seatClass +'" seatid="'+ b.id +'" state="'+ b.state +'" price="'+ b.price +'">'+ 
                    seatName +'<span>'+ seatPrice +'</span></li>';
            })
            newHtml += '</ul></li>';
            $(tripBox).append(newHtml);
        });

        // 绑定座位点击事件
        $(tripBox).find(".seat-list li[state=0]").bind('click',function(){
            var $this = $(this);
            var $car = $this.closest("[carid]");
            var carIndex = $car.attr("index");
            var selected = $car.find(".car-info em");
            var selectedNum = parseInt($(selected).text());
            var seatId = $this.attr("seatid");
            var seatList = _this.selectedInfo.cars[carIndex].seats;
            var price = parseInt($this.attr("price"));
            var nowPrice = parseInt(_this.selectedInfo.price);
            if($this.hasClass("active")) {
                $this.removeClass("active");
                $(selected).text(selectedNum-1);
                seatList.splice($.inArray(seatId,seatList),1);
                _this.selectedInfo.price = parseFloat(nowPrice - price).toFixed(0);
                $(totalPrice).text("¥ "+ _this.selectedInfo.price);
            }
            else {
                $this.addClass("active");
                $(selected).text(selectedNum+1);
                seatList.push(seatId);
                _this.selectedInfo.price = parseFloat(nowPrice + price).toFixed(0);
                $(totalPrice).text("¥ "+ _this.selectedInfo.price);
            }
            console.log(_this.selectedInfo.cars);
        });
        
    }
}

// 日历
var indexSchedule = new Schedule({
    el: '#schedule-box',
    clickCb: function (y,m,d) {
        var month = m,
            day = d;
        if(m.toString().length==1) month = "0"+m;
        if(d.toString().length==1) day = "0"+d;
        var date = y+"-"+month+"-"+day;
        $(result.dateSelect)
        .attr("date",date)
        .val(datelist.dateToText(date));
        result.scheduleHide();

        // 选择日期后重新加载数据
        result.loadList();
    }
});

result.init();